﻿#define _CRT_SECURE_NO_WARNINGS 1

#include "SeqList.h"

//初始化
void SLInit(SeqList* ps)
{
	assert(ps);
	ps->arr = NULL;
	ps->capacity = 0;
	ps->length = 0;
}

//扩容
void SLCheckCapacity(SeqList* ps)
{
	int newCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
	SLDataType* tmp = (SLDataType*)realloc(ps->arr, newCapacity * sizeof(SLDataType));
	if (tmp == NULL)
	{
		perror("realloc");
		return;
	}
	//扩容成功
	ps->arr = tmp;
	ps->capacity = newCapacity;
}

//尾部插⼊
void SLPushBack(SeqList* ps, SLDataType x)
{
	assert(ps);
	if (ps->length == ps->capacity)
	{
		//空间不够,扩容
		SLCheckCapacity(ps);
	}
	//空间足够
	ps->arr[ps->length] = x;
	ps->length++;
}

//头部插⼊
void SLPushFront(SeqList* ps, SLDataType x)
{
	assert(ps);
	if (ps->length == ps->capacity)
	{
		//空间不够,扩容
		SLCheckCapacity(ps);
	}
	//判断线性表为空的情况
	if (ps->length == 0)
	{
		ps->arr[0] = x;
		ps->length++;
	}
	int i = 0;
	for (i = ps->length - 1; i >= 0; i--)
	{
		ps->arr[i + 1] = ps->arr[i];
	}
	ps->arr[0] = x;
	ps->length++;
}

//尾部删除
void SLPopBack(SeqList* ps)
{
	assert(ps);
	//判断线性表为空的情况
	if (ps->length == 0)
	{
		return;
	}
	//不为空
	ps->length--;
}

//头部删除
void SLPopFront(SeqList* ps)
{
	assert(ps);
	//判断线性表为空的情况
	if (ps->length == 0)
	{
		return;
	}
	//不为空
	int i = 0;
	for (i = 1; i < ps->length; i++)
	{
		ps->arr[i - 1] = ps->arr[i];
	}
	ps->length--;
}

//指定位置之前插⼊数据
void SLInsert(SeqList* ps, int pos, SLDataType x)
{
	assert(ps);
	if (ps->length == ps->capacity)
	{
		//空间不够,扩容
		SLCheckCapacity(ps);
	}
	int i = 0;
	for (i = ps->length - 1; i >= pos; i--)
	{
		ps->arr[i + 1] = ps->arr[i];
	}
	ps->arr[pos] = x;
	ps->length++;
}

///指定位置删除数据
void SLErase(SeqList* ps, int pos)
{
	assert(ps);
	//判断线性表为空的情况
	if (ps->length == 0)
	{
		return;
	}
	int i = 0;
	for (i = pos; i < ps->length; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->length--;
}

//查找数据
int SLFind(SeqList* ps, SLDataType x)
{
	assert(ps);
	//判断线性表为空的情况
	if (ps->length == 0)
	{
		return;
	}
	int i = 0;
	for (i = 0; i < ps->length; i++)
	{
		if (ps->arr[i] == x)
		{
			return i;
		}
	}
	return -1;
}

//打印
void SLPrint(SeqList* ps)
{
	int i = 0;
	for (i = 0; i < ps->length; i++)
	{
		printf("%d ", ps->arr[i]);
	}
}

//销毁
void SLDestroy(SeqList* ps)
{
	free(ps->arr);
	ps->arr = NULL;

	ps->capacity = ps->length = 0;
}